package per.turtle.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import per.turtle.common.core.exception.CustomException;
import per.turtle.common.core.utils.SecurityUtils;
import per.turtle.system.entity.*;
import per.turtle.system.mapper.*;
import per.turtle.system.service.ISysConfigService;
import per.turtle.system.service.ISysUserService;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户 服务层实现
 *
 * @author turtle
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    private final SysRoleMapper roleMapper;

    private final SysPostMapper postMapper;

    private final SysUserRoleMapper userRoleMapper;

    private final SysUserPostMapper userPostMapper;

    private final ISysConfigService configService;

    @Override
    public boolean checkEmailUnique(SysUser user) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(StrUtil.isNotBlank(user.getEmail()), SysUser::getEmail, user.getEmail())
               .ne(user.getUserId() != null, SysUser::getUserId, user.getUserId());
        List<SysUser> infos = baseMapper.selectList(wrapper);
        return infos.isEmpty();
    }

    @Override
    public boolean checkPhoneUnique(SysUser user) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(StrUtil.isNotBlank(user.getPhoneNumber()), SysUser::getPhoneNumber, user.getPhoneNumber())
               .ne(user.getUserId() != null, SysUser::getUserId, user.getUserId());
        List<SysUser> infos = baseMapper.selectList(wrapper);
        return infos.isEmpty();
    }

    @Override
    public void checkUserAllowed(SysUser user) {
        if (BeanUtil.isNotEmpty(user.getUserId()) && SysUser.isAdmin(user.getUserId())) {
            throw new CustomException("不允许操作超级管理员用户");
        }
    }

    @Override
    public boolean checkUserNameUnique(SysUser user) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(StrUtil.isNotBlank(user.getUserName()), SysUser::getUserName, user.getUserName())
               .ne(user.getUserId() != null, SysUser::getUserId, user.getUserId());
        List<SysUser> infos = baseMapper.selectList(wrapper);
        return infos.isEmpty();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(List<String> userIds) {
        for (String userId : userIds) {
            checkUserAllowed(new SysUser(userId));
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return baseMapper.deleteBatchIds(userIds);
    }

    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (BeanUtil.isEmpty(userList) || userList.size() == 0) {
            throw new CustomException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigValueByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = baseMapper.selectUserByUserName(user.getUserName());
                if (BeanUtil.isEmpty(u)) {
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUserName()).append(" 导入成功");
                } else if (isUpdateSupport) {
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUserName()).append(" 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、账号 ").append(user.getUserName()).append(" 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = baseMapper.insert(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    @Override
    public void insertUserAuth(String userId, String[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    @Override
    public int resetPwd(SysUser user) {
        return baseMapper.updateById(user);
    }

    @Override
    public int resetUserPwd(String userName, String password) {
        return baseMapper.resetUserPwd(userName, password);
    }

    @Override
    public List<SysUser> selectAllocatedList(SysUser user) {
        return baseMapper.selectAllocatedList(user);
    }

    @Override
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return baseMapper.selectUnallocatedList(user);
    }

    @Override
    public SysUser selectUserById(String userId) {
        return baseMapper.selectUserById(userId);
    }

    @Override
    public SysUser selectUserByUserName(String userName) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SysUser::getUserName, userName);
        return baseMapper.selectUserByUserName(userName);
    }

    @Override
    public List<SysUser> selectUserList(SysUser user) {
        Wrapper<SysUser> wrapper = new QueryWrapper<>(user);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        StringBuilder idsStr = new StringBuilder();
        for (SysPost post : list) {
            idsStr.append(post.getPostName()).append(StrUtil.COMMA);
        }
        if (StrUtil.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        StringBuilder idsStr = new StringBuilder();
        for (SysRole role : list) {
            idsStr.append(role.getRoleName()).append(StrUtil.COMMA);
        }
        if (StrUtil.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUser user) {
        String userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return baseMapper.updateById(user);
    }

    @Override
    public boolean updateUserAvatar(SysUser user) {
        return baseMapper.updateById(user) > 0;
    }

    @Override
    public int updateUserProfile(SysUser user) {
        return baseMapper.updateById(user);
    }

    @Override
    public int updateUserStatus(SysUser user) {
        return baseMapper.updateById(user);
    }

    private void insertUserPost(SysUser user) {
        List<String> posts = user.getPostIds();
        if (BeanUtil.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<>();
            for (String postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0) {
                userPostMapper.batchUserPost(list);
            }
        }
    }

    private void insertUserRole(String userId, String[] roleIds) {
        if (BeanUtil.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<>();
            for (String roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    private void insertUserRole(SysUser user) {
        List<String> roles = user.getRoleIds();
        if (BeanUtil.isNotEmpty(roles)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<>();
            for (String roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

}
